package com.bungarus.model;

import io.netty.channel.ChannelId;

/**
 * Created by tang on 2018/11/12.
 */
public class SessionBuilder {
    private static final SnowflakeIdMaker idMaker = new SnowflakeIdMaker(0,0);
    private Session session;

    public SessionBuilder(Session session){
        this.session = session;
    }

    public SessionBuilder id(ChannelId id) {
        session.setId(id.asLongText());
        return this;
    }

    public SessionBuilder user(String userId){
        session.setUserId(userId);
        return this;
    }

    public SessionBuilder tenant(String tenantId){
        session.setTenantId(tenantId);
        return this;
    }

    public SessionBuilder device(String device){
        session.setDev(device);
        return this;
    }

    public SessionBuilder app(String app){
        session.setApp(app);
        return this;
    }

    public SessionBuilder ip(String ip){
        session.setIp(ip);
        return this;
    }

    public SessionBuilder port(int port){
        session.setPort(port);
        return this;
    }

    public SessionBuilder token(String token){
        if(null == token){
            session.setToken(String.valueOf(idMaker.nextId()));
        }
        else {
            session.setToken(token);
        }
        return this;
    }

    public Session build(){
        session.setCreated(System.currentTimeMillis());
        session.setKey(KeyGenerator.generate(16));
        return session;
    }

    final static private class KeyGenerator {
        private static char[] charset = {'0','1','2','3','4','5','6','7','8','9','a','A','b','B','c','C','d','D','e',
            'E','f','F','g','G','h','H','i','I','j','J','k','K','l','L','m','M','n','N','o','O','p','P','q','Q','s',
            'S','t','T','u','U','w','W','x','X','y','Y','z','Z','@','#','*','~','^'};

        static String generate(int keyLength){
            if(keyLength <= 0){
                throw new IllegalArgumentException("key length null");
            }

            long index;
            StringBuffer sb = new StringBuffer();
            for(int i=0;i<keyLength;i++){
                index = Math.round(Math.random() * charset.length);
                if(index >= charset.length){
                    index = index % charset.length;
                }
                sb.append(charset[(int)index]);
            }
            return sb.toString();
        }
    }
}
